package cn.edu.scau.vsac.controller;

import cn.edu.scau.vsac.common.Constants;
import cn.edu.scau.vsac.common.ResultData;
import cn.edu.scau.vsac.entity.User;
import cn.edu.scau.vsac.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Tag(name = "登陆")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(path = "/register", method = RequestMethod.POST)
    @Operation(summary = "register")
    public ResultData<Map<String, Object>> register(Model model, @RequestBody User user) {
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()) {
//            model.addAttribute("msg", "注册成功,您的账号已经可以正常使用了!");
            map.put("msg", "注册成功,您的账号已经可以正常使用了!");
            return ResultData.success(map);
        } else {
//            model.addAttribute("usernameMsg", map.get("usernameMsg"));
//            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return ResultData.success(map);
        }
    }

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    @Operation(summary = "login")
    public ResultData<Boolean> login(String username, String password, Model model, HttpServletResponse response) {
        int expiredSeconds = 3600 * 12;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
//            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            return ResultData.success(true);
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return ResultData.fail(Constants.ResponseCode.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    @Operation(summary = "logout")
    public ResultData<Boolean> logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        return ResultData.success(true);
    }

}
